/*
 * $Id: LastfmTopAlbums.java 362 2008-04-14 19:14:12Z jasta $
 *
 * Copyright (C) 2008 Josh Guilfoyle <jasta@devtcg.org>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2, or (at your option) any
 * later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 */

package org.devtcg.five.music.activity;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

import org.devtcg.five.music.R;
import org.devtcg.five.music.lastfm.TopAlbumsByUser;
import org.devtcg.five.provider.Five;
import org.devtcg.five.util.ThreadStoppable;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewInflate;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class LastfmTopAlbums extends Activity
{
	private static final String TAG = "LastfmTopAlbums";

	/* XXX: Hardcoded! */
	private static final String USER = "jasta";

	private ProgressDialog mProgress;
	
	private ListView mList;
	
	private Cursor mCursor;
	
	private Handler mHandler = new Handler();
	private ThreadStoppable mWorker;
	
	private boolean mShutdown = false;
	
	@Override
	public void onCreate(Bundle icicle)
	{
		super.onCreate(icicle);
		setContentView(R.layout.lastfm_top_albums);

		mList = (ListView)findViewById(android.R.id.list);
		mList.setOnItemClickListener(mClickEvent);

		accessLastfm();
	}
	
	private final SimpleCursorAdapter.ViewBinder mDefaultAlbumCover = new SimpleCursorAdapter.ViewBinder()
	{
		public boolean setViewValue(View v, Cursor c, int col)
		{
			if (v instanceof ImageView)
			{
				String value = c.getString(col);
		
				ImageView iv = (ImageView)v;
				
				if (value == null)
					iv.setImageResource(R.drawable.lastfm_cover_small);
				else
					iv.setImageURI(Uri.parse(value));

				return true;
			}
			
			return false;
		}
	};

	private final OnItemClickListener mClickEvent = new OnItemClickListener()
	{
		public void onItemClick(AdapterView av, View v, int pos, long id)
		{
			Uri chosen = Five.Music.Albums.CONTENT_URI.buildUpon()
			  .appendPath(String.valueOf(id))
			  .build();

			startActivity(new Intent(Intent.VIEW_ACTION, chosen,
			  LastfmTopAlbums.this, AlbumSongList.class));
		}
	};

	private void accessLastfm()
	{
		mProgress = ProgressDialog.show(this, "Accessing Last.fm...",
		  "Please wait while Five downloads Last.fm meta data...", true, true,
		  mCanceled);

		mWorker = new ThreadStoppable()
		{
			public void run()
			{
				final TopAlbumsByUser meta =
				  new TopAlbumsByUser(getContentResolver(), USER, 20);

				try
				{
					meta.fetch();
				}
				catch (Exception e)
				{
					final String msg = e.toString();

					if (mStopped == true)
						return;

					mHandler.post(new Runnable() {
						public void run()
						{
							Toast.makeText(LastfmTopAlbums.this, "BUG: " + msg,
							  Toast.LENGTH_SHORT).show();
						}
					});
				}

				if (mStopped == true)
					return;

				mHandler.post(new Runnable() {
					public void run()
					{
						if (meta != null)
							initFromMeta(meta);

						Log.d(TAG, "All done!");
						mProgress.dismiss();

						mWorker = null;
					}
				});
			}
		};

		mWorker.start();
	}
	
	private final OnCancelListener mCanceled = new OnCancelListener()
	{
		public void onCancel(DialogInterface i)
		{
			finish();
		}
	};

	private void shutdown()
	{
		if (mWorker == null)
			return;

		mWorker.interruptAndStop();

		while (true)
		{
			try { mWorker.join(); break; }
			catch (InterruptedException e) { }
		}

		mWorker = null;
	}

	@Override
	public void onDestroy()
	{
		Log.d(TAG, "Toodles!");
		
		shutdown();
		super.onDestroy();
	}

	private void initFromMeta(TopAlbumsByUser meta)
	{
		List<TopAlbumsByUser.Album> albums = meta.getAlbums();
		
		if (albums == null || albums.isEmpty() == true)
		{
			mList.setVisibility(View.GONE);
			findViewById(android.R.id.empty).setVisibility(View.VISIBLE);
		}
		else
		{
			Cursor c = expandToCursor(albums);

			assert c != null;
			assert c.count() > 0;

			SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
			  R.layout.album_list_item, c,
			  new String[] { "artwork", "full_name", "artist" },
			  new int[] { R.id.album_cover, R.id.album_name, R.id.artist_name });
			  
			adapter.setViewBinder(mDefaultAlbumCover);
			
			mList.setAdapter(adapter);

			mCursor = c;
		}
	}
	
	private Cursor expandToCursor(List<TopAlbumsByUser.Album> albums)
	{
		Uri uri = 
		  Uri.parse("content://org.devtcg.five/media/music/albums");

		String[] proj = {
			"_id", "name", "full_name", "artwork", "artist",	
		};

		Cursor c = managedQuery(uri, proj, getWhere(albums), null, null);
		
		return c;
	}
	
	private String getWhere(List<TopAlbumsByUser.Album> albums)
	{
		assert albums.isEmpty() == false;

		StringBuffer b = new StringBuffer("a._id IN (");

		Iterator<TopAlbumsByUser.Album> i = albums.iterator();

		assert i.hasNext() == true;
		b.append(i.next().albumId);

		while (i.hasNext() == true)
		{
			b.append(',');
			b.append(i.next().albumId);
		}

		b.append(')');

		return b.toString();
	}

//	private static class Adapter extends BaseAdapter
//	{
//		private Context mContext;
//		private ViewInflate mInflate;
//
//		private List<TopAlbumsByUser.Album> mAlbums;
//
//		public Adapter(Context ctx, List<TopAlbumsByUser.Album> albums)
//		{
//			mContext = ctx;
//			mAlbums = albums;
//			mInflate = ViewInflate.from(ctx);
//		}
//
//		public int getCount()
//		{
//			return mAlbums.size();
//		}
//
//		public Object getItem(int position)
//		{
//			return mAlbums.get(position);
//		}
//
//		public long getItemId(int position)
//		{
//			return mAlbums.get(position).albumId;
//		}
//
//		public View getView(int position, View convertView, ViewGroup parent)
//		{
//			View v;
//
//			if (convertView != null)
//				v = convertView;
//			else
//				v = mInflate.inflate(R.layout.album_list_item, null, null);
//			
//
//			
//			return null;
//		}
//	}
}
